package com.info3k.client.components;

import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.info3k.client.Info3K;
import com.info3k.client.commands.event.EventCommand;

public class Search extends Composite {
	
	private TextBox input = new TextBox();
	private Button search = new Button(Info3K.msgs.searchEvents());
	
	public Search(final Info3K info3k){
		final VerticalPanel panel = new VerticalPanel();
		
		initWidget(panel);
		
		panel.setWidth("100%");
		
		input.setValue(Info3K.msgs.enterSearchTerm());
		search.setEnabled(false);
		
        input.addFocusHandler(new FocusHandler(){
			public void onFocus(FocusEvent event) {
				if(input.getText()==""){
					input.setText(Info3K.msgs.enterSearchTerm());
					search.setEnabled(false);
				} else if(input.getText().equals(Info3K.msgs.enterSearchTerm())){
					input.setText("");
					search.setEnabled(true);
				}
			}
        });
        
        input.addBlurHandler(new BlurHandler(){
			public void onBlur(BlurEvent event) {
				if(input.getText()==""){
					input.setText(Info3K.msgs.enterSearchTerm());
					search.setEnabled(false);
				} else if(input.getText().equals(Info3K.msgs.enterSearchTerm())){
					input.setText("");
					search.setEnabled(true);
				}
			}
        });
        
        input.addKeyPressHandler(new KeyPressHandler(){
			public void onKeyPress(KeyPressEvent event) {
				if(event.getCharCode() == 13){
					search.click();
				}
			}
        });
        
        search.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				EventCommand cmd = new EventCommand(RootPanel.get("right_section"), info3k, input.getText());
				cmd.execute();
			}
        });
				
		input.setWidth("150px");
		search.setWidth("120px");
		search.setHeight("28px");
		search.getElement().getStyle().setProperty("marginTop", "5px");
		input.getElement().getStyle().setProperty("marginTop", "3px");
		panel.add(input);
		panel.add(search);
		
		panel.setCellHorizontalAlignment(input, HorizontalPanel.ALIGN_CENTER);
		panel.setCellHorizontalAlignment(search, HorizontalPanel.ALIGN_CENTER);
	}
}
